package com.iespring.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * urlutil, 需要实例化使用， 使用@Autoware实例化
 * @param null
 * @return 
 * @author 杨宇健
 * @since 2022/12/29 10:46 
 */
@Component
public class UrlUtil {

    @Value("${file.uploadDir}")
    String fileDir;

    private static String serverPort;

    @Value("${server.port}")
    private String port;

    @PostConstruct
    public void setServerPort(){
        this.serverPort= port;
    }

    //获取url http部分前缀
    public String getUrl() {
        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "http://"+address.getHostAddress() +":"+ UrlUtil.serverPort;
    }
    
    //传入相对路径，拼接成完全的url
    public String getUrl(String suffix){

        //处理空值
        if (suffix == null) {
            return null;
        }

        String prefix = getUrl();
        if (!suffix.startsWith("/")) {
            suffix = "/" + suffix;
        }
        return prefix + suffix;
    }

    //拼接两个路径，保证两个路径能以 且仅以 一个 "/" 拼接
    public String concatPath(String path1, String path2){
        if (path2.startsWith("/")) {
            path2.replaceFirst("/", "");
        }
        String path = "";
        if (path1.endsWith("/")) {
            path = path1 + path2;
        }else {
            path = path1 + "/" + path2;
        }
        return path;
    }

    //根据传入的相对路径获取本地绝对路径
    public String getLocalPath(String relativaPath){
        return concatPath(fileDir, relativaPath);
    }

    //根据传入的绝对路径或者网址获得相对路径
    public String getRelativePath(String path){
        if (path.startsWith(getUrl())) {
            return path.split(getUrl())[1];
        }
        else if (path.startsWith("http")){
            return path;
        }
        return path.split(fileDir + "/")[1];
    }

}
